package rabbitmq.simple;

import com.rabbitmq.client.*;
import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class ConsumerDemo {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        // 1.创建连接
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("47.122.121.191");
        factory.setPort(5672);
        factory.setUsername("admin");
        factory.setPassword("admin");
        factory.setVirtualHost("new virtual");
        Connection connection = factory.newConnection();
        // 2.创建Channel
        Channel channel = connection.createChannel();
        // 3.声明队列（如果队列已经存在可省略，如果不存在省略此声明的话会报错，建议不要省略）
        channel.queueDeclare("hello2",true,false,false,null);
        // 4.消费消息
        /**
         * basicConsume(String queue, boolean autoAck, Consumer callback)
         * 参数说明：
         * queue：队列名称
         * autoAck：是否自动确认
         * callback：接收到消息之后，执行的逻辑
         */
        Consumer consumer = new DefaultConsumer(channel){
            // 从队列中收到消息，就会执行的方法
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                // TODO
                System.out.println("接收到消息：" + new String(body));
            }
        };

        channel.basicConsume("hello2",true,consumer);
        // 等待程序执行完成
        Thread.sleep(2000);
        // 5.释放资源
        channel.close();
        connection.close();
    }
}
